package com.attendance.www.hr.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.attendance.www.hr.beans.UserEmployeeBean;
import com.attendance.www.hr.constant.AppConstant;
import com.attendance.www.hr.service.IUserService;
import com.zhangkongli.frame.core.ResultMap;
import com.zhangkongli.frame.utils.JSONUtils;

public class LoginInterceptor extends HandlerInterceptorAdapter{
	
	@Resource
	private IUserService userService;
    
    private Logger log = Logger.getLogger(LoginInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception 
	{
		//获得请求方式 
		String method=request.getMethod();
		if(!method.equals("POST") && !method.equals("GET")){
			return responseHandle(response,"非法请求！");
		}
		
		Enumeration<String> ss=request.getParameterNames();
		
		String url = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
		//判断等于重置密码链接
		if(url.equals("/user/resetPassWord.do")) {
			UserEmployeeBean userEmployee = (UserEmployeeBean)request.getSession().getAttribute(AppConstant.SESSIONUSER);
			if(userEmployee==null) {
				//TODO check
				String key=request.getParameter("key");
			}
		}else if(!url.equals("/user/login.do") 
				&& !url.equals("/user/logout.do") 
				&& !url.equals("/user/getVerificationPassword.do")  
				&& !url.equals("/user/changepassword.do") 
				&& !url.equals("/user/getUserData.do")
				&& !url.equals("/user/getCSRFToken.do")
				&& !url.equals("/user/forgetPassword.do")
				&& !url.equals("/user/checkKey.do")
				&& !url.equals("/user/doResetPassword.do")
				&& !url.equals("/user/getSingleSignOn.do")
				&& !url.equals("/interface/receiveApproval.do")
				&& !url.equals("/interface/getAttendanceDateByEmployeeNo.do")
				&& !url.equals("/interface/applyTravel.do")){
			
			//返回请求行中的参数部分
			String allow=request.getParameter("allow");
			if(allow!=null && allow.contains("true")) {
				return true;
			}
			
			//返回请求行中的参数部分
			String token=request.getParameter("token");
			UserEmployeeBean userEmployee = (UserEmployeeBean)request.getSession().getAttribute(AppConstant.SESSIONUSER);
			if(userEmployee == null) {
				return responseHandle(response,"您尚未登录或登录超时,请先登录!");
			}
			else{
				String message = "";
				message += "用户:" + userEmployee.getChineseName() + "(" + userEmployee.getEmployeeNo() + ") ====>";
				message += "登录IP:" + request.getRemoteAddr() + ",";
				message += "请求接口" + url;
				log.info(message);
				//比较验证用户身份
				/*if(token==null){
					return responseHandle(response,"未传递身份验证编码!");
				}else{
					if(token.equals(userEmployee.getToken())){
						return true;
					}else{
						return responseHandle(response,"身份验证编码不正确，请重新登录!");
					}
				}*/
			}
		}else{
			/*if(url.equals("/user/login.do")){
				//非法的跨站请求校验
				if(!verifyCSRFToken(request)){
					return responseHandle(response,"非法请求!");
				}
			}*/
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}
	
	private boolean responseHandle(HttpServletResponse response,String contextStr) throws Exception{
		Map<String,Object> map = ResultMap.fault("00001", contextStr);
		String context = JSONUtils.getJSONString(map);
		PrintWriter out = null;
		response.setStatus(HttpServletResponse.SC_FORBIDDEN);
		response.setContentType("application/json; charset=utf-8");
		try {
			out = response.getWriter();
		} catch (IOException e) {
			return false;
		}
		out.write(context);
		out.flush();
		out.close();
		return false;
	}
	
	/** <一句话功能简述>
     * 处理跨站请求伪造
     * 针对需要登录后才能处理的请求,验证CSRFToken校验
     * @author  tangguilin
     * @param request
     */
    protected boolean verifyCSRFToken(HttpServletRequest request){
        String requstCSRFToken = request.getHeader("CSRFToken");  //请求中的CSRFToken
        if (StringUtils.isEmpty(requstCSRFToken)){
            return false;
        }
        String sessionCSRFToken = (String)request.getSession().getAttribute("CSRFToken");
        if (StringUtils.isEmpty(sessionCSRFToken)){
            return false;
        }
        return requstCSRFToken.equals(sessionCSRFToken);
    }
}
